﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.Reflection;
using Opalis.QuickIntegrationKit;
using System.Management;

namespace Erlacher.Opalis.VMMExtended
{
    [OpalisObject("Refresh Host", ShowFilters = false)]
    public class RefreshHost : IOpalisObject 
    {
        private Settings settings;
        private string s_name = string.Empty;


        [OpalisConfiguration]
        public Settings Settings
        {
            set { settings = value; }
            get { return settings; }
        }

        [OpalisInput("Host Name")]
        public string Name
        {
            set { s_name  = value; }
            get { return ""; }
        }
        

        public void Design(IOpalisDesigner designer)
        {

            designer.AddOutput("ErrorState");
            designer.AddOutput("ErrorMessage");
            designer.AddOutput("Trace");
           
        }

        public void Execute(IOpalisRequest request, IOpalisResponse response)
        {

            string psscript = "";
            PowerShellHelper.ReturnObject Results;


            Assembly _assembly = Assembly.GetExecutingAssembly();
            StreamReader _textStreamReader = new StreamReader(_assembly.GetManifestResourceStream("Erlacher.Opalis.VMMExtended.PSScripts.RefreshHost.ps1"));
            psscript = _textStreamReader.ReadToEnd();

            psscript = psscript.Replace("%HOSTNAME%", this.s_name  );


            Results = PowerShellHelper.RunScript(psscript.ToString(), settings.DomainName + @"\" + settings.UserName , settings.Password , settings.VMMServer  );

            Dictionary<string, object> publishedData = new Dictionary<string, object>();

 
            publishedData.Add("ErrorState", Results.ErrorState.ToString());
            publishedData.Add("ErrorMessage", Results.ErrorMessage );
            publishedData.Add("Trace", Results.Trace );


            response.Publish(publishedData);
            
             
        }
    }
}